package com.twq.collection.list.highorder

/**
 * Created by tangweiqun on 2017/12/10.
 */
object Forth {
  def main(args: Array[String]): Unit = {

    val list = List(1, 7, 2, 9)
    list.reduce((a, b) => a - b)
    list.reduce(_ - _) //((1 - 7) - 2) - 9 = 1 - 7 - 2 - 9 = -17
    list.reduceLeft(_ - _) //((1 - 7) - 2) - 9 = 1 - 7 - 2 - 9 = -17
    list.reduceRight(_ - _) //1 - (7 - (2 - 9)) = -13

    list.fold(0)((a, b) => a - b)
    list.fold(0)(_ - _) //(((0 - 1) - 7) - 2) - 9 = -19
    list.foldLeft(0)(_ - _) //(((0 - 1) - 7) - 2) - 9 = -19
    (0 /: list) (_ - _) //同 foldLeft
    list.foldRight(0)(_ - _) //1 - (7 - (2 - (9 - 0))) = -13
    (list :\ 0) (_ - _) //同foldRight

    //不同点一：
    val words = List("the", "quick", "brown", "fox")

    words.reduceLeft(_ + "," + _)

    words.foldLeft("")(_ + "," + _)

    words.tail.foldLeft(words.head)(_ + "," + _)

    //不同点二：fold的返回类型是任意类型，而reduce的只能是集合类型或者其子类
    import scala.collection.mutable.Map
    val freq = Map[Char, Int]()
    for (c <- "MyyyyDoggggg") freq(c) = freq.getOrElse(c, 0) + 1

    "MyyyyDoggggg".toList.foldLeft(Map.empty[Char, Int])((m, c) => m += (c -> (m.getOrElse(c, 0) + 1)))


    //使用foldLeft来实现reverse
    def reverseLeft[T](xs: List[T]) =
      xs.foldLeft(List[T]()) { (ys, y) => y :: ys }
  }
}
